package com.example.socketchat.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class MockClientRunner implements ApplicationRunner {

    @Value("${socket.server.port}")
    private int serverPort;
    
    private static final int CLIENT_COUNT = 5;
    private final List<MockClient> clients = new ArrayList<>();

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 等待服务器启动完成
        TimeUnit.SECONDS.sleep(2);
        
        // 启动多个模拟客户端
        for (int i = 1; i <= CLIENT_COUNT; i++) {
            String clientId = "client" + i;
            MockClient client = new MockClient(clientId, "localhost", serverPort);
            
            try {
                client.start();
                clients.add(client);
                log.info("模拟客户端 {} 启动成功", clientId);
            } catch (Exception e) {
                log.error("模拟客户端 {} 启动失败", clientId, e);
            }
            
            // 避免同时启动多个客户端
            TimeUnit.MILLISECONDS.sleep(500);
        }
        
        // 添加关闭钩子，在JVM退出时关闭所有客户端
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("关闭所有模拟客户端...");
            clients.forEach(MockClient::stop);
        }));
    }
} 